Overview of Math in JavaScript

Numbers

JavaScript supports integer and floating point numbers. The numbers 17 and 3.14159 are valid JavaScript numeric literals. These are strings of characters which JavaScript interprets as meaning a number.

JavaScript understands octal, hexadecimal and decimal integers. In addition to integers such as 27 or 89, which JavaScript interprets in base-10, you may use base-eight (octal) and base-16 (hexadecimal) numbers in your scripts by using the prefixes "0" and "0x". For example, the number 16 equates to 020 in octal and 0x10 in hexadecimal. Valid integers include:

  • 98
  • 0xffff
  • 0377
  • Floating points are comprised of several optional parts. Floating point numbers start with an decimal integer followed by a decimal point, a fraction and an exponent. Exponents are marked with "e" or "E" and followed by an integer. Valid floating point numbers include:
  • 2.7
  • -2.7E15
  • .2e-5
  • 2E2
  • A special number, NaN, handles error conditions. These conditions include dividing by zero or trying to evaluate a nonnumeric text string such as "f23". You can usually treat this "Not a Number" as a zero.

    Type some numbers and press the evaluate button to see how JavaScript evaluates your numbers. This script uses the built-in functions parseInt() and parseFloat().

    Your Number:
    As an Integer
    as a Float


    Operators

    JavaScript supports a variety of mathematical operators. These operators follow standard "C" precedence.

    + addition - subtraction
    * multiplication / division
    % modulus ++ increment
    -- decrement - unary negation
    & bitwise AND | bitwise OR
    ^ bitwise XOR << left shift
    >> right shift >>> zerofill right shift


    Built In Functions

    JavaScript's Math object provides built-in functionality. The Math object allows access to a wide range of mathematical functions.

    Category Function Example
    Scale Maximum Math.max(5,99)
    Minimum Math.min(5,99)
    Abs. Value Math.abs(-151.15)
    Rounding Round Math.round(1.15)
    Ceiling Math.ceil(1.15)
    Floor Math.floor(1.15)
    Trig Sine Math.sin(3.14159)
    Cosine Math.cos(3.14159)
    Tangent Math.tan(0)
    Arcsine Math.asin(-1)
    Arccosine Math.acos(-1)
    Arctan Math.atan(0)
    Exponentiation 2^Exponent Math.exp(1)
    Natural Log Math.log(2.7)
    Power a^b Math.pow(5,2)
    Roots Square Root Math.sqrt(100)

    Type a JavaScript expression in the field below. Press the evaluate button to see how JavaScript evaluates your numbers. Try, for example, Math.sqrt(49). Make sure to keep track of upper- and lowercase in your expressions.

    Expression: 

    Value:


    Constants

    JavaScript's Math object includes a number of constants. These constants include pi, e, and several other frequently used numeric values. Select any of the following constants to view them.

    value

    Copyright ©2000 by Charles River Media, All Rights Reserved